# tkinter 图形化用户页面 GUI
from tkinter import *
import tkinter.messagebox


r = Tk()
r.wm_minsize(400, 160)
r.title("计算器")
show = Entry(r, width=30, justify="right", font=12)
show.grid(row=0, column=0, columnspan=5)


# 清屏按钮事件
def clean_show():
    show.delete(0, END)


# 退格按钮事件
def back_s():
    le = len(show.get())
    show.delete(le-1, END)


# 计算结果事件
def cal():
    try:
        res = round(eval(show.get()), 2)
    except Exception as e:
        # 错误提示
        tkinter.messagebox.showinfo("提示", e)
        return
    clean_show()
    show.insert(0, str(res))


# 显示按钮上的符号
def s(snw, v):
    snw.insert(END, v)


n1 = Button(r, text="1", width=8, height=2, command=lambda: s(show, "1"))
n1.grid(row=1, column=0)
n2 = Button(r, text="2", width=8, height=2, command=lambda: s(show, "2"))
n2.grid(row=1, column=1)
n3 = Button(r, text="3", width=8, height=2, command=lambda: s(show, "3"))
n3.grid(row=1, column=2)
n4 = Button(r, text="4", width=8, height=2, command=lambda: s(show, "4"))
n4.grid(row=1, column=3)
n5 = Button(r, text="5", width=8, height=2, command=lambda: s(show, "5"))
n5.grid(row=1, column=4)
n6 = Button(r, text="6", width=8, height=2, command=lambda: s(show, "6"))
n6.grid(row=2, column=0)
n7 = Button(r, text="7", width=8, height=2, command=lambda: s(show, "7"))
n7.grid(row=2, column=1)
n8 = Button(r, text="8", width=8, height=2, command=lambda: s(show, "8"))
n8.grid(row=2, column=2)
n9 = Button(r, text="9", width=8, height=2, command=lambda: s(show, "9"))
n9.grid(row=2, column=3)
n0 = Button(r, text="0", width=8, height=2, command=lambda: s(show, "0"))
n0.grid(row=2, column=4)

no = Button(r, text=".", width=8, height=2, command=lambda: s(show, "."))
no.grid(row=3, column=0)
np = Button(r, text="+", width=8, height=2, command=lambda: s(show, "+"))
np.grid(row=3, column=1)
nm = Button(r, text="-", width=8, height=2, command=lambda: s(show, "-"))
nm.grid(row=3, column=2)
nr = Button(r, text="x", width=8, height=2, command=lambda: s(show, "*"))
nr.grid(row=3, column=3)
nd = Button(r, text="/", width=8, height=2, command=lambda: s(show, "/"))
nd.grid(row=3, column=4)


nc = Button(r, text="C", width=16, height=2, command=clean_show)
nc.grid(row=4, column=0, columnspan=2)
ne = Button(r, text="=", width=16, height=2, command=cal)
ne.grid(row=4, column=2, columnspan=2)
nt = Button(r, text="<-", width=8, height=2, command=back_s)
nt.grid(row=4, column=4)

r.mainloop()
